<?php
/**
 * abstract model class with db relation
 *
 * @author raphael seebacher <raphasee@ee.ethz.ch>
 * @version 0.01
 */
abstract class db_model {
    protected $data;
    protected static $dbc = NULL;

    abstract public function save();

    public function __construct($data=NULL) {
        self::$dbc = db_controller::get_instance();

        if ($data != NULL) {
            try {
                $this->set_all($data);
            }
            catch (model_exception $e) {

            }
        }
    }

    public function set($key, $value) {
        if (array_key_exists($key, $this->data)) {
            $this->data[$key] = $value;
            return true;
        }
        else {
            throw new model_exception('Key "'.$key.'" not valid for model');
        }
    }
    
    public function set_all($data_array) {
        foreach ($this->data as $key => $value) {
            if (!array_key_exists($key, $data_array)) {
                throw new model_exception('Not all required data provided.');
            }
        }

        foreach ($this->data as $key => $value) {
            $this->set($key,$data_array[$key]);
        }
    }

    public function get($key=NULL) {
        if ($key == NULL) {
            return $this->data;
        }
        else if (array_key_exists($key, $this->data)) {
            return $this->data[$key];
        }
        else {
            return false;
        }
    }

    public function get_all() {
        $result = Array();

        foreach (array_keys($this->data) as $key) {
            $result[$key] = $this->get($key);
        }

        return $result;
    }

    protected function escape_data() {
        foreach ($this->data as $key => $value) {
            $this->data[$key] = self::$dbc->escape($value);
        }
    }
}
?>